package com.dai.spec.gxk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dai.spec.common.constant.RoleConstants;
import com.dai.spec.common.core.domain.entity.SysUser;
import com.dai.spec.common.enums.CourseStatus;
import com.dai.spec.common.enums.CourseType;
import com.dai.spec.common.enums.SelectStatus;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.SecurityUtils;
import com.dai.spec.gxk.domain.Course;
import com.dai.spec.gxk.domain.Student;
import com.dai.spec.gxk.domain.StudentCourse;
import com.dai.spec.gxk.domain.Teacher;
import com.dai.spec.gxk.mapper.*;
import com.dai.spec.gxk.request.MyStudentPageRequest;
import com.dai.spec.gxk.request.MyStudentScorePageRequest;
import com.dai.spec.gxk.service.MyStudentService;
import com.dai.spec.gxk.vo.MyStudentScoreVO;
import com.dai.spec.gxk.vo.MyStudentVO;
import com.dai.spec.gxk.vo.ScoreVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 我的学生管理
 */
@Service
public class MyStudentServiceImpl implements MyStudentService {
    private TeacherMapper teacherMapper;

    private MyStudentMapper mapper;
    private StudentMapper studentMapper;
    private final SelectedCourseMapper selectedCourseMapper;
    private CourseMapper courseMapper;


    public MyStudentServiceImpl(TeacherMapper teacherMapper, MyStudentMapper mapper, StudentMapper studentMapper, SelectedCourseMapper selectedCourseMapper, CourseMapper courseMapper) {
        this.teacherMapper = teacherMapper;
        this.mapper = mapper;
        this.studentMapper = studentMapper;
        this.selectedCourseMapper = selectedCourseMapper;
        this.courseMapper = courseMapper;
    }

    /**
     * 分页查询我的学生列表
     *
     * @param pageRequest
     * @return
     */
    @Override
    public List<MyStudentVO> queryMyStudentList(MyStudentPageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        SysUser user = SecurityUtils.getLoginUser().getUser();

        Long roleId = user.getRoles().get(0).getRoleId();
        if (!RoleConstants.TEACHER.equals(roleId)) {
            throw new BaseException("当前登录用户不为教师，无权限！");
        }


        String jobNumber = user.getUserName();
        if (StringUtils.isNotBlank(jobNumber)) {
            LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teacher::getJobNumber, jobNumber);
            Teacher teacher = teacherMapper.selectOne(queryWrapper);
            if (null != teacher) {
                String teacherName = teacher.getName();
                pageRequest.setTeacherName(teacherName);
                Page<MyStudentVO> myStudentVOPage = mapper.queryMyStudentList(pageRequest);
                return myStudentVOPage;

            }
        }
        return null;
    }

    /**
     * 学生成绩列表
     *
     * @param pageRequest
     * @return
     */
    @Override
    public List<MyStudentScoreVO> queryMyStudentScoreList(MyStudentScorePageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        SysUser user = SecurityUtils.getLoginUser().getUser();

        Long roleId = user.getRoles().get(0).getRoleId();
        if (!RoleConstants.TEACHER.equals(roleId)) {
            throw new BaseException("当前登录用户不为教师，无权限！");
        }


        String jobNumber = user.getUserName();
        if (StringUtils.isNotBlank(jobNumber)) {
            LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teacher::getJobNumber, jobNumber);
            Teacher teacher = teacherMapper.selectOne(queryWrapper);
            String teacherName = teacher.getName();
            pageRequest.setTeacherName(teacherName);
            Page<MyStudentScoreVO> myStudentScoreVOS = mapper.queryMyStudentScoreList(pageRequest);
            return myStudentScoreVOS;
        }
        return null;
    }

    /**
     * 根据id查询学生成绩
     *
     * @param id
     * @return
     */
    @Override
    public ScoreVO getById(Long id) {
        Student student = studentMapper.selectById(id);
        String studentNumber = student.getStudentNumber();
        LambdaQueryWrapper<StudentCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourse::getStudentNumber, studentNumber)
                .eq(StudentCourse::getSelectStatus, SelectStatus.SELECTED.getCode());
        StudentCourse studentCourse = selectedCourseMapper.selectOne(queryWrapper);
        BigDecimal score = studentCourse.getScore();
        ScoreVO scoreVO = new ScoreVO();
        scoreVO.setId(id);
        scoreVO.setScore(score);
        scoreVO.setStudentNumber(studentNumber);
        scoreVO.setSelectTime(studentCourse.getSelectTime());
        return scoreVO;
    }

    /**
     * 修改学生成绩，打分
     */
    @Override
    @Transactional
    public int updateScore(StudentCourse studentCourse) {
        //课程状态为关闭，不能再次进行打分
        Long studentNumber = studentCourse.getStudentNumber();
        LambdaQueryWrapper<StudentCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourse::getStudentNumber, studentNumber);
        List<StudentCourse> studentCourseList = selectedCourseMapper.selectList(queryWrapper);

        studentCourseList.stream()
                .map(item -> item.getCourseId())
                .forEach(courseId -> {
                    Course course = courseMapper.selectById(courseId);
                    if (CourseStatus.CLOSE.getCode().equals(course.getStatus())) {
                        throw new BaseException("该课程已关闭，不能进行打分");
                    }
                });
        for (StudentCourse course : studentCourseList) {
            Long courseId = course.getCourseId();
            studentCourse.setCourseId(courseId);
        }

        int rows = 0;
        BigDecimal score = studentCourse.getScore();
        LambdaUpdateWrapper<StudentCourse> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StudentCourse::getStudentNumber, studentNumber)
                .set(StudentCourse::getScore, score);
        rows = selectedCourseMapper.update(null, updateWrapper);
        // 打分次数 +1
        LambdaUpdateWrapper<StudentCourse> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StudentCourse::getStudentNumber, studentNumber)
                .eq(StudentCourse::getCourseId, studentCourse.getCourseId())
                .setSql("mark_counts = mark_counts + 1");

        selectedCourseMapper.update(null, wrapper);

        LambdaQueryWrapper<StudentCourse> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(StudentCourse::getStudentNumber, studentNumber)
                .eq(StudentCourse::getCourseId, studentCourse.getCourseId())
                .eq(StudentCourse::getSelectTime,studentCourse.getSelectTime());
        StudentCourse course = selectedCourseMapper.selectOne(wrapper);
        Integer markCounts = course.getMarkCounts();
        if (markCounts == 1) {
            updateStudentCredits(studentCourse, studentNumber);
        }
        return rows;
    }

    private void updateStudentCredits(StudentCourse studentCourse, Long studentNumber) {
        BigDecimal score = studentCourse.getScore();

        BigDecimal sixty = new BigDecimal("60");
        //打完分后，课程成绩大于60，则发放学分给学生
        if (score.compareTo(sixty) > 0) {

            Long courseId = studentCourse.getCourseId();
            LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            courseLambdaQueryWrapper.eq(Course::getId, courseId);
            Course course = courseMapper.selectOne(courseLambdaQueryWrapper);
            String type = course.getType();
            BigDecimal credits = course.getCredits();

            //根据公选课的类型更新相应的类型学分
            String[] types = {CourseType.SHEHUIKEXUE.getCode(), CourseType.ZIRANKRXUE.getCode(),
                    CourseType.WENXUEYISHU.getCode(), CourseType.CHUANGXINCHUANGYE.getCode()};
            String[] fields = {"sk_credit", "zk_credit", "wy_credit", "cc_credit"};

            for (int i = 0; i < types.length; i++) {
                if (type.equals(types[i])) {
                    LambdaUpdateWrapper<Student> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(Student::getStudentNumber, studentNumber)
                            .setSql(fields[i] + " = " + fields[i] + " + " + credits);
                    studentMapper.update(null, updateWrapper);
                    break;
                }
            }

            // 更新公选课总学分
            LambdaUpdateWrapper<Student> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Student::getStudentNumber, studentNumber)
                    .setSql("course_credit = course_credit + " + credits);
            studentMapper.update(null, updateWrapper);


        }
    }
}
